package cn.com.filemanager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhaokk
 * @since 2024/7/20
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 访问登录页面之前所访问的页面，可通过这个值跳转至之前的页面
        String returnUri = request.getParameter("return_uri");
        RequestDispatcher rd = null;
        if (username == null || password == null) {
            request.setAttribute("msg", "用户名或密码为空");
            rd = request.getRequestDispatcher("/login.jsp");
            rd.forward(request, response);
        } else {
            if (username.equals(SystemConfig.getConfig().get("username")) && password.equals(SystemConfig.getConfig().get("password"))) {
                /* 登录成功 */
                // 将登录状态保存到session对象中
                request.getSession().setAttribute("flag", "login_success");
                /* 判断登录之前的上一个页面是否存在 */
                if (returnUri != null && returnUri.length() > 0) {
                    // 存在则跳转到登录之前的界面
                    rd = request.getRequestDispatcher(returnUri);
                    rd.forward(request, response);
                } else {
                    // 不存在则跳转到首页
                    rd = request.getRequestDispatcher("/index.jsp");
                    rd.forward(request, response);
                }
            } else {
                /* 登录失败 */
                // 将登录状态修改为失败
                request.getSession().setAttribute("flag", "login_error");
                request.setAttribute("msg", "用户名或密码错误");
                // 失败后跳转到登录界面
                rd = request.getRequestDispatcher("/login.jsp");
                rd.forward(request, response);
            }
        }
    }

}
